﻿using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using DreamStore.WebShop.Extensibility;
using DreamStore.WebShop.ViewModels;
using Orchard.Environment.Extensions;

namespace DreamStore.WebShop.Services
{
    [OrchardFeature("DreamStore.WebShop.SimulatedPSP")]
    public class SimulatedPaymentServiceProvider : IPaymentServiceProvider
    {
        public void RequestPayment(PaymentRequest request)
        {
            var rvd = new RouteValueDictionary
                      {
                          {"action", "Index"},
                          {"controller", "SimulatedPaymentServiceProvider"},
                          {"area", "DreamStore.WebShop"},
                          {"orderReference", request.Order.Number},
                          {"amount", (int) (request.Order.Total*100)}
                      };
            
            //request.ActionResult = new RedirectToRouteResult(rvd);
            request.WillHandlePayment = true;
            request.PaymentServiceProviderViewModels.Add(new PaymentServiceProviderViewModel
            {
                ProviderName = "Simulator",
                ImageName = "simulator.jpg",
                RouteValues = rvd,
            });
        }

        public void ProcessResponse(PaymentResponse response)
        {
            if (response.WillHandleResponse)
            {
                return;
            }
            var result = response.HttpContext.Request.QueryString["result"];
            response.OrderReference = response.HttpContext.Request.QueryString["orderReference"];
            response.PaymentReference = response.HttpContext.Request.QueryString["paymentId"];
            response.ResponseText = response.HttpContext.Request.QueryString.ToString();
            switch (result)
            {
                case "Success":
                    response.Status = PaymentResponseStatus.Success;
                    response.WillHandleResponse = true;
                    break;

                case "Failure":
                    response.Status = PaymentResponseStatus.Failed;
                    response.WillHandleResponse = true;
                    break;

                case "Cancelled":
                    response.Status = PaymentResponseStatus.Cancelled;
                    response.WillHandleResponse = true;
                    break;

                default:
                    response.WillHandleResponse = false;
                    break;
            }
            
        }
    }
}